package com.edu.chapter07;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.Layout;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

public class MyTextView extends AppCompatTextView {
    private Paint underlinePaint;
    private final float underlineHeight = 2f; // 下划线高度（单位px）

    public MyTextView(@NonNull Context context) {
        super(context);
        init();

    }

    public MyTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();

    }

    public MyTextView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        underlinePaint = new Paint();
        underlinePaint.setColor(Color.RED); // 下划线颜色
        underlinePaint.setStrokeWidth(underlineHeight);
    }

    @Override
    protected void onDraw(Canvas canvas) {
//        super.onDraw(canvas); // 先绘制文字
//        // 计算下划线位置（文字底部）
//        float baseline = getBaseline(); // 文字基线Y坐标
//        canvas.drawLine(0, baseline + underlineHeight,
//                getWidth(), baseline + underlineHeight,
//                underlinePaint);
        super.onDraw(canvas); // 先绘制文字
        Layout layout = getLayout(); // 获取文本布局对象
        if (layout == null) return;

        // 遍历每一行文本
        for (int i = 0; i < layout.getLineCount()-1; i++) {
            float baseline = layout.getLineBaseline(i); // 当前行基线
            canvas.drawLine(
                    100,
                    baseline + underlineHeight, // 下划线在基线下方
                    getWidth()-100,
                    baseline + underlineHeight,
                    underlinePaint
            );
        }
    }
}